package com.bruce.learnrecylerview.app.store;

import com.bruce.learnrecycler.kotlin.ui.listitem.Item;
import com.bruce.learnrecylerview.app.action.MainActions;
import com.github.bluzwang.fluxsupport.Action;
import com.github.bluzwang.fluxsupport.Dispatcher;
import com.github.bluzwang.fluxsupport.Store;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by wangzhijie@wind-mobi.com on 2015/9/1.
 */
@Deprecated
public class MainStore extends Store {
    private List<Item> items = new ArrayList<>();

    @Inject
    public MainStore(Dispatcher dispatcher) {
        super(dispatcher);
    }

    @Override
    final protected void onRequestAction(Action action) {
        switch (action.getType()) {
            case MainActions.SHOW_PD_BUS:
            case MainActions.SHOW_PX_BUS:
                Item item = (Item) action.getData(MainActions.KEY_RESULT_ITEM);
                int index = (int) action.getData(MainActions.KEY_ITEM_INDEX);
                if (index > items.size()) {
                    index = items.size() - 1;
                }
                items.add(index, item);
                responseToUiWithType(MainActions.UI_ADD_ONE_ITEM)
                        .and(MainActions.KEY_ITEM_INDEX, index)
                        .post();
                break;
        }
    }

    public void requestRemoveItem(int index) {
        items.remove(index);
        responseToUiWithType(MainActions.UI_REMOVE_ONE_ITEM)
                .and(MainActions.KEY_ITEM_INDEX, index)
                .post();
    }

    public void requestSwapItem(int from, int to) {
        Collections.swap(items, from, to);
        responseToUiWithType(MainActions.UI_SWAP_ONE_ITEM)
                .and(MainActions.KEY_ITEM_INDEX, from)
                .and(MainActions.KEY_ITEM_INDEX2, to)
                .post();
    }

    @Override
    protected Dispatcher.ResponseBuilder responseToUiWithType(String type) {
        return super.responseToUiWithType(type).and(MainActions.KEY_DATAS, items);
    }
}
